import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store';

import 'amfe-flexible';
import 'default-passive-events';

import Vant from 'vant';
import 'vant/lib/index.css';
import 'vant/lib/icon/local.css';
Vue.use(Vant);
import { Toast } from 'vant';
Vue.use(Toast);
Toast.setDefaultOptions({ duration: 3000 });  

// 自定义组件引入
import myComponent from '@/pages/components';
Vue.use(myComponent);

Vue.config.productionTip = false;

// 请求公共方法封装
import axios from './axios';
Vue.prototype.$axios = axios;

// 微信封装方法
import tool from '@/util/tool.js';
Vue.prototype.$tool = tool;

String.prototype.search = function(name) {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  let str = this;
  if (this[0] == '?') str = this.substr(1);
  let result = str.match(reg);
  return result ? result[2] : '';
}

// 路由守卫
router.beforeEach((to, from, next) => {
  if(to.name == 'login') {  
    localStorage.clear();    
    store.commit('setState', { userInfo: {} });
    next(); 
  } else if(store.state.userInfo.token) { 
    next(); 
  } else {
    store.commit('getUserInfo');
    if (store.state.userInfo.token) { next(); }
    else { next('login'); }
  }
});

Vue.filter('formatLength', function(target) {
  if (target.length > 20){
    return target.substring(0,20) + '...';
  } else {
    return target;
  }
});

// 复制的公共方法
Vue.prototype.$copy = function(value) {
  let textarea = document.createElement("textarea"); 
  // textarea.style = 'display: none;';
  textarea.value = value;

  let currentFocus = document.activeElement;
  let toolBoxwrap = document.getElementById('app');       
  toolBoxwrap.appendChild(textarea); 
  
  textarea.focus();
  if (textarea.setSelectionRange) {
    textarea.setSelectionRange(0, textarea.value.length); 
  } else {
    textarea.select();
  }
    
  let flag = false;
  try {
    flag = document.execCommand("copy");
  } catch (err) {
    flag = false;
  }

  toolBoxwrap.removeChild(textarea); 
  currentFocus.focus();
  
  if (flag) this.$toast('复制成功：' + value);
  else this.$toast('复制失败');
};

export const app = new Vue({
  router,
  store,
  el: '#app',
  render: h => h(App)
});
